define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'xyvenue_vue'], function ($, undefined, Backend, Table, Form,Vue) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'xyvenue/venue/index' + location.search,
                    add_url: 'xyvenue/venue/add',
                    edit_url: 'xyvenue/venue/edit',
                    del_url: 'xyvenue/venue/del',
                    multi_url: 'xyvenue/venue/multi',
                    import_url: 'xyvenue/venue/import',
                    table: 'xyvenue_venue',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'weigh',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'store.name', title: __('Store_id')},
                        {field: 'name', title: __('Name'), operate: 'LIKE'},
                        {field: 'duration', title: __('Duration'), searchList: {"30":__('Duration 30'),"45":__('Duration 45'),"60":__('Duration 60'),"90":__('Duration 90')}, formatter: Table.api.formatter.normal},
                        {field: 'status', title: __('Status'), searchList: {"normal":__('Status normal'),"hidden":__('Status hidden')}, formatter: Table.api.formatter.status},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            //修改默认弹窗大小
            Fast.config.openArea = ['70%', '90%'];

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        select: function () {
		    // 初始化表格参数配置
		    Table.api.init({
		        extend: {
		            index_url: 'xyvenue/venue/select?store_id='+Config.store_id,
		        }
		    });
		    var urlArr = [];
		
		    var table = $("#table");
		
		    table.on('check.bs.table uncheck.bs.table check-all.bs.table uncheck-all.bs.table', function (e, row) {
		        if (e.type == 'check' || e.type == 'uncheck') {
		            row = [row];
		        } else {
		            urlArr = [];
		        }
		        $.each(row, function (i, j) {
		            if (e.type.indexOf("uncheck") > -1) {
		                var index = urlArr.indexOf(j.id);
		                if (index > -1) {
		                    urlArr.splice(index, 1);
		                }
		            } else {
		                urlArr.indexOf(j.id) == -1 && urlArr.push(j.id);
		            }
		        });
		    });
		
		    // 初始化表格
		    table.bootstrapTable({
		        url: $.fn.bootstrapTable.defaults.extend.index_url,
		        sortName: 'id',
		        showToggle: false,
		        showExport: false,
		        columns: [
		            [
		                {checkbox: true},
                        {field: 'id', title: __('Id')},
                        //{field: 'store.name', title: __('Store_id')},
                        {field: 'name', title: __('Name'), operate: 'LIKE'},
                        {field: 'duration', title: __('Duration'), searchList: {"30":__('Duration 30'),"45":__('Duration 45'),"60":__('Duration 60'),"90":__('Duration 90')}, formatter: Table.api.formatter.normal},
                        {field: 'status', title: __('Status'), searchList: {"normal":__('Status normal'),"hidden":__('Status hidden')}, formatter: Table.api.formatter.status},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
		                {
		                    field: 'operate', title: __('Operate'), events: {
		                        'click .btn-chooseone': function (e, value, row, index) {
		                            var multiple = Backend.api.query('multiple');
		                            multiple = multiple == 'true' ? true : false;
		                            Fast.api.close(row);
		                        },
		                    }, formatter: function () {
		                        return '<a href="javascript:;" class="btn btn-danger btn-chooseone btn-xs"><i class="fa fa-check"></i> ' + __('Choose') + '</a>';
		                    }
		                }
		            ]
		        ]
		    });
		
		    // 选中多个
		    $(document).on("click", ".btn-choose-multi", function () {
		        var multiple = Backend.api.query('multiple');
		        multiple = multiple == 'true' ? true : false;
		        Fast.api.close({url: urlArr.join(","), multiple: multiple});
		    });
		
		    // 为表格绑定事件
		    Table.api.bindevent(table);
		},
        add: function () {

            var venue = new Vue({
                el: "#app",
                data() {
                    return {
                        storeInfo:'',
                        areaList:[],
                        duration:60,
                        timePriceList:[],
                        isholidayprice:0,
                        holidaypriceList:[],
                    }
                },
                methods: {
                    //添加区域
                    addArea() {
                        this.areaList.push({
                            name: '',
                        })
                    },
                    //删除区域
                    deleteArea(k) {
                        this.areaList.splice(k, 1)
                    },

                    //选择场馆
                    selectStore(){
                        var that = this;
                        parent.Fast.api.open("xyvenue/store/store/select?multiple=false", __('选择'), {
                            area: ['80%', '80%'],
                            callback: function (data) {
                                that.storeInfo = data
                                that.timePriceList = [];
                                that.setTimeprice();
                            }
                        });
                    },

                    //更改起订时长
                    changeDuration(){
                        this.duration = parseInt($("#c-duration").val());
                        if(this.storeInfo != ''){
                            this.setTimeprice();
                            this.setHolidayprice();
                        }
                        
                    },

                    //是否启用公休日和节假日特价
                    changeIsholidayprice(){
                        this.isholidayprice = parseInt($("#c-isholidayprice").val());
                        if(this.storeInfo != '' && this.isholidayprice == 1){
                            this.setHolidayprice();
                        }
                    },

                    //生成收费时段
                    setTimeprice(){
                        var businesshours = this.storeInfo.businesshours;
                        var timeArr = businesshours.split('-');
                        var startTime = timeArr[0];
                        var endTime = timeArr[1];
                        var duration = parseInt(this.duration);
                        const start = new Date();
                        start.setHours( parseInt(startTime.split(':')[0]), parseInt(startTime.split(':')[1]), 0);
                        const end = new Date();
                        end.setHours( parseInt(endTime.split(':')[0]), parseInt(endTime.split(':')[1]), 0);
                        var timePriceList = [];
                        while (start <= end) {
                            timePriceList.push({time:start.toLocaleString('zh-CN', {hour: '2-digit', minute: '2-digit'}),price:''});
                            start.setMinutes(start.getMinutes() + duration);
                        }
                        this.timePriceList = timePriceList;
                    },

                    //生成公休节假日收费时段
                    setHolidayprice(){
                        var businesshours = this.storeInfo.businesshours;
                        var timeArr = businesshours.split('-');
                        var startTime = timeArr[0];
                        var endTime = timeArr[1];
                        var duration = parseInt(this.duration);
                        const start = new Date();
                        start.setHours( parseInt(startTime.split(':')[0]), parseInt(startTime.split(':')[1]), 0);
                        const end = new Date();
                        end.setHours( parseInt(endTime.split(':')[0]), parseInt(endTime.split(':')[1]), 0);
                        var holidaypriceList = [];

                        while (start <= end) {
                            holidaypriceList.push({time:start.toLocaleString('zh-CN', {hour: '2-digit', minute: '2-digit'}),price:''});
                            start.setMinutes(start.getMinutes() + duration);
                        }

                        this.holidaypriceList = holidaypriceList;
                    }
                                        
                },
                
            })

            Form.api.bindevent($("form[role=form]"), function(data, ret){
                console.log(data,ret);
            }, function(data, ret){
                console.log(data,ret);
            }, function(success, error){
                //提交之前设置数据
                var areaList = venue.areaList;

                if(areaList.length == 0){
                    Toastr.error("区域不能为空");
                    return false;
                }

                var tempAreaList = [];
                var falgSame = false;
                areaList.forEach((item,index)=>{
                    if( tempAreaList.indexOf(item.name) != -1){
                        falgSame = true;
                    }
                    tempAreaList.push(item.name);
                });

                if(falgSame){
                    Toastr.error("存在重复区域请删除在提交");
                    return false;
                }

                $("#area").val(JSON.stringify(areaList));

                var timePriceList = venue.timePriceList;
                if(timePriceList.length == 0){
                    Toastr.error("时段收费不能为空");
                    return false;
                }
                $("#timeprice").val(JSON.stringify(timePriceList));

                var holidaypriceList = venue.holidaypriceList;
                if(holidaypriceList.length == 0 && venue.isholidayprice == 1){
                    Toastr.error("公休日和节假日特价时段收费不能为空");
                    return false;
                }
                $("#holidayprice").val(JSON.stringify(holidaypriceList));

                Form.api.submit($("form[role=form]"), function (data, ret) {
                    setTimeout(function () {
                        parent.Layer.close(parent.Layer.getFrameIndex(window.name));
                        window.parent.location.reload();
                    }, 600);
                });

                return false;
            });

        },
        edit: function () {
            var venue = new Vue({
                el: "#app",
                data() {
                    return {
                        storeInfo:Config.storeInfo,
                        areaList:Config.row.area,
                        duration:Config.row.duration,
                        timePriceList:Config.row.timeprice,
                        isholidayprice:Config.row.isholidayprice,
                        holidaypriceList:Config.row.holidayprice?Config.row.holidayprice:[],
                    }
                },
                methods: {
                    //添加区域
                    addArea() {
                        this.areaList.push({
                            name: '',
                        })
                    },
                    //删除区域
                    deleteArea(k) {
                        this.areaList.splice(k, 1)
                    },

                    //选择场馆
                    selectStore(){
                        var that = this;
                        parent.Fast.api.open("xyvenue/store/store/select?multiple=false", __('选择'), {
                            area: ['80%', '80%'],
                            callback: function (data) {
                                that.storeInfo = data;
                                that.timePriceList = [];
                                that.setTimeprice();
                            }
                        });
                    },

                    //更改起订时长
                    changeDuration(){
                        this.duration = parseInt($("#c-duration").val());
                        if(this.storeInfo != ''){
                            this.setTimeprice();
                            this.setHolidayprice();
                        }
                        
                    },

                    //是否启用公休日和节假日特价
                    changeIsholidayprice(){
                        this.isholidayprice = parseInt($("#c-isholidayprice").val());
                        if(this.storeInfo != '' && this.isholidayprice == 1){
                            this.setHolidayprice();
                        }
                    },

                    //生成收费时段
                    setTimeprice(){
                        var businesshours = this.storeInfo.businesshours;
                        var timeArr = businesshours.split('-');
                        var startTime = timeArr[0];
                        var endTime = timeArr[1];
                        var duration = parseInt(this.duration);
                        const start = new Date();
                        start.setHours(parseInt(startTime.split(':')[0]), parseInt(startTime.split(':')[1]), 0);
                        const end = new Date();
                        end.setHours( parseInt(endTime.split(':')[0]), parseInt(endTime.split(':')[1]), 0);

                        var timePriceList = [];
                        while (start <= end) {
                            timePriceList.push({time:start.toLocaleString('zh-CN', {hour: '2-digit', minute: '2-digit'}),price:''});
                            start.setMinutes(start.getMinutes() + duration);
                        }

                        this.timePriceList = timePriceList;
                    },

                    //生成公休节假日收费时段
                    setHolidayprice(){
                        var businesshours = this.storeInfo.businesshours;
                        var timeArr = businesshours.split('-');
                        var startTime = timeArr[0];
                        var endTime = timeArr[1];
                        var duration = parseInt(this.duration);
                        const start = new Date();
                        start.setHours( parseInt(startTime.split(':')[0]), parseInt(startTime.split(':')[1]), 0);
                        const end = new Date();
                        end.setHours( parseInt(endTime.split(':')[0]), parseInt(endTime.split(':')[1]), 0);
                        var holidaypriceList = [];

                        while (start <= end) {
                            holidaypriceList.push({time:start.toLocaleString('zh-CN', {hour: '2-digit', minute: '2-digit'}),price:''});
                            start.setMinutes(start.getMinutes() + duration);
                        }

                        this.holidaypriceList = holidaypriceList;
                    }
                                        
                },
                
            })

            Form.api.bindevent($("form[role=form]"), function(data, ret){
                console.log(data,ret);
            }, function(data, ret){
                console.log(data,ret);
            }, function(success, error){
                //提交之前设置数据
                var areaList = venue.areaList;

                if(areaList.length == 0){
                    Toastr.error("区域不能为空");
                    return false;
                }

                var tempAreaList = [];
                var falgSame = false;
                areaList.forEach((item,index)=>{
                    if( tempAreaList.indexOf(item.name) != -1){
                        falgSame = true;
                    }
                    tempAreaList.push(item.name);
                });

                if(falgSame){
                    Toastr.error("存在重复区域请删除在提交");
                    return false;
                }

                $("#area").val(JSON.stringify(areaList));

                var timePriceList = venue.timePriceList;
                if(timePriceList.length == 0){
                    Toastr.error("时段收费不能为空");
                    return false;
                }
                $("#timeprice").val(JSON.stringify(timePriceList));

                var holidaypriceList = venue.holidaypriceList;
                if(holidaypriceList.length == 0 && venue.isholidayprice == 1){
                    Toastr.error("公休日和节假日特价时段收费不能为空");
                    return false;
                }
                $("#holidayprice").val(JSON.stringify(holidaypriceList));

                Form.api.submit($("form[role=form]"), function (data, ret) {
                    setTimeout(function () {
                        parent.Layer.close(parent.Layer.getFrameIndex(window.name));
                        window.parent.location.reload();
                    }, 600);
                });

                return false;
            });
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});
